#!/bin/sh
#
# ocos common variables and functions
# author: g_CAPD_SRDC_OS@tencent.com
#

. /usr/lib/opencloudos-tools/sys-manage/ocos-backup.sh
. /usr/lib/opencloudos-tools/sys-manage/ocos-analyze-performance.sh
OC_RELEASE="/etc/opencloudos-release"
KERNEL_VER=$(uname -r)
OC_VER_V=""
OC_VER=""
OC_DATE=""



#get tlinux version and date
getVersionDate()
{
    if [ -f /etc/motd ]; then
        OC_VER=$(awk '/OpenCloudOS/{print $NF}' /etc/opencloudos-release)
    fi
    if [ -f $OC_RELEASE ]; then
        OC_VER_V=$(head $OC_RELEASE)
    fi
        
}

#check machine type, dependent on virt-what
vmwhat()
{
    if [ ! -x /usr/sbin/virt-what ]; then
        echo "Try to install virt-what rpm by yum!"
        yum -y install virt-what > /dev/null 2>&1
    fi
    if [ -x /usr/sbin/virt-what ]; then
	echo -e -n "Machine type:\t\t"
        v_what=$(/usr/sbin/virt-what)
        [ -z "$v_what" ] && echo "Physical machine" && return 0
        echo $v_what | grep -q -i "virtualbox"  && echo "Virtualbox guest" && return 0
        echo $v_what | grep -q -i "vmware" && echo "VMware guest" && return 0
        echo "$v_what"
        return 0
    fi
}

#show opencloudos system information
ocos_show()
{
    echo "=============== System Information ==============="
    # get SN
    if [ -x /usr/sbin/dmidecode ]; then
        seri_num=$(dmidecode -s system-serial-number | tail -n1)
	[ -n "$seri_num" ] && echo -e "Serial Number:\t\t$seri_num"
    fi

    # get IP
    eth1_ip=$(ip a | grep "inet" | grep "eth1" | awk '{print $2}' | awk -F/ '{print $1}')
    if [ -n "$eth1_ip" ]; then
        echo -e "eth1 IP:\t\t$eth1_ip"
    else
        other_ip=$(ip a|grep "inet"|grep -v "inet6"|grep -v "127.0"|head -n1|awk '{print $2}'|awk -F/ '{print $1}')
	[ -n "$other_ip" ] && echo -e "IP:\t\t$other_ip"
    fi

    # get machine type
    if which rpm &> /dev/null ;then
        vmwhat
    fi

    # get system version
    [ -n "$KERNEL_VER" ] && echo -e "Kernel version:\t\t$KERNEL_VER"

    getVersionDate
    if [ -n "$OC_VER_V" ]; then
        echo -e "OpenCloudOS release:\t$OC_VER_V"
    elif [ -f /etc/os-release ]; then
	echo -e -n "OS release:\t\t"
	awk -F'"' '/PRETTY_NAME/ {print $2}' /etc/os-release
    fi

    if [ -n "$OC_VER" ]; then 
        echo -e "Release version:\t$OC_VER"
    fi
    if [ -n "$OC_DATE" ]; then
	echo -e "Release date:\t\t$OC_DATE"
    fi

    # get rpm version
    if which rpm &> /dev/null ;then
        GCC_VERSION=$(rpm -q gcc | grep -v "not" | head -n1)
        [ -n "$GCC_VERSION" ] && echo -e "Gcc version:\t\t$GCC_VERSION"
        GLIBC_VERSION=$(rpm -q glibc | grep -v "not" | head -n1)
        [ -n "$GLIBC_VERSION" ] && echo -e "Glibc version:\t\t$GLIBC_VERSION"
        SYSTEMD_VERSION=$(rpm -q systemd | grep -v "not" | head -n1)
        [ -n "$SYSTEMD_VERSION" ] && echo -e "Systemd version:\t$SYSTEMD_VERSION"
        PYTHON_VERSION=$(rpm -q python | grep -v "not" | head -n1)
        [ -n "$PYTHON_VERSION" ] && echo -e "Python version:\t\t$PYTHON_VERSION"
    fi
}


#opencloudos check rpms
ocos_check()
{
    if [ -n "$1" ]; then
        rpm -qa | grep $1 > /tmp/rpms_list.txt
    else
        echo "It may take few minitues!"
        rpm -qa > /tmp/rpms_list.txt
	
        
    fi
    for i in $(cat /tmp/rpms_list.txt)
    do
        result=$(rpm -q -V $i)
        if [ -n "$result" ]; then
            echo "$i:"
            echo $result
        fi
    done
}


#opencloudos update rpms
ocos_update()
{
    if [ -n "$1" ]; then
        yum update $@
    else
        yum update
    fi
}

#opencloudos install rpms
ocos_install()
{
    if [ -n "$1" ]; then
        yum install $@
    else
        echo "You Nedd to pass a list of pkgs to install"
    fi
}


# Yum Check Available Package Updates
ocos_check_update()
{
    #To see which installed packages on your system have updates available, use the following command
    yum check-update
}

# Recover or Reinstall the system
ocos_recover()
{
    /usr/lib/opencloudos-tools/sys-manage/opencloudos_super_tool.py -r $@
}

# System Health Check
ocos_check_health()
{
    health_op=$1
    health_output_path=$2
    if [ "$health_op"x == "-o"x ]; then
        if [ -d "$health_output_path" ]; then
            /usr/lib/opencloudos-tools/sys-manage/ocos-check-health.sh | tee ${health_output_path}/health_check_`date +%Y%m%d_%H%M%S`.txt
            echo "Your health check report has been saved at ${health_output_path}."
        else
            echo "Output path does not exists."
            mkdir -p /data/opencloudos/health-check
            /usr/lib/opencloudos-tools/sys-manage/ocos-check-health.sh | tee /data/opencloudos/health-check/health_check_`date +%Y%m%d_%H%M%S`.txt
            echo "Your health check report has been saved at /data/opencloudos/health-check."
        fi
    else
	/usr/lib/opencloudos-tools/sys-manage/ocos-check-health.sh
    fi
}

ops()
{
	local TOP=/usr/lib/opencloudos-tools RUN=ops-run DSC=ops-help sub=ops help= bad=

	if [ "$1" = "--bashcomp" ]; then
		shift
		help=comp
		#bashcomp mode, ignore debug
		[ "$1" = "-d" ] && shift
		#no completion if -v
		[ "$1" = "-v" ] && exit 0
	else
		if [ "$1" = "-d" ]; then
			shift
			set -x
		fi

		if [ "$1" = "-v" ]; then
			read help < $TOP/ops/VERSION
			echo oc-ops v$help
			exit 0
		fi
	fi

	while [ $# -gt 0 ]; do
		if [ -x "$TOP/$sub/$RUN" ]; then
			break
		elif [ "$1" = "-h" -o "$1" = "help" ]; then
			[ "$help" = "comp" ] && exit 0
			help=help
			break
		elif [[ "$1" =~ ^[^a-zA-Z0-9] || "$1" =~ [^-_.a-zA-Z0-9] ]]; then
			bad=1
			break
		elif [ -d "$TOP/$sub/$1" ]; then
			sub="$sub/$1"
			shift
		else
			bad=1
			#bad cmd found, no bashcomp available
			[ -n "$bashcomp" ] && exit 0
			break
		fi
	done

	if [ -z "$bad" -a -x "$TOP/$sub/$RUN" ]; then
		#leaf cmd found, no bashcomp available
		if [ "$help" != "comp" ]; then
			#run cmd with remain args
			exec "$TOP/$sub/$RUN" "$@"
			exit 255
		fi
		# do leaf cmd completion
		sub="$sub/ocos-comp"
		while [ $# -gt 0 ]; do
			sub="$sub.$1"
			shift
		done
		[ -r "$TOP/$sub.txt" ] && cat "$TOP/$sub.txt"
		exit 0
	fi

	if [ -z "$help" ]; then
		# print error message if not bashcomp
		local ops="${sub//\// }"
		[ $# -gt 0 ] && echo ERROR: ocos $ops: command \"$1\" invalid
		echo Available command for '"'ocos $ops'"':
	fi

	cd "$TOP/$sub" || exit 1

	local msg op n=0 w=0
	declare -a ops msgs files

	if [ "$help" = "comp" ]; then
		# bashcomp only search one level commands
		files=( * )
	else
		# -h/help print all sub commands
		IFS=$'\n' files=( $(find . -type d -name "[a-zA-Z0-9]*" -print) )
	fi

	for op in "${files[@]}"; do
		# strip leadding ./
		op="${op#./}"
		#filter out invalid characters
		[[ "$op" =~ (^|/)[^a-zA-Z0-9] ]] && continue
		[[ "$op" =~ [^-_.a-zA-Z0-9/] ]] && continue
		#need non-empty, readable $DSC file
		[ -r "$op/$DSC" ] || continue
		read msg < "$op/$DSC"
		[ -z "$msg" ] && continue

		if [ "$help" = "comp" ]; then
			# bashcomp don't like tab
			#ATTN: tab after double //, convert tab to space
			msg=${msg//	/ }
		else
			# convert / to space
			op="${op//\// }"
		fi

		#save and update max-width
		[ ${#op} -gt $w ] && w=${#op}
		eval 'ops['$n']="$op"'
		eval 'msgs['$n']="$msg"'
		n=$((n+1))
	done

	#show results
	w="%-${w}s  %s\n"
	op=0
	while [ $op -lt $n ]; do
		printf "$w" "${ops[$op]}" "${msgs[$op]}"
		op=$((op+1))
	done

	exit 0
}
